package com.think.admin.web.service.impl;

import com.think.admin.cons.AdminCons;
import com.think.admin.model.dto.user.UserRoleDto;
import com.think.admin.web.mapper.UserRoleMapper;
import com.think.admin.web.service.IUserRoleService;
import com.think.common.enums.IsDeleteEnum;
import com.think.common.enums.StateEnum;
import com.think.common.exception.SysException;
import com.think.common.utils.SysUtils;
import com.think.common.web.service.impl.SuperServiceImpl;
import com.think.dao.entity.UserRole;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author xwj
 * @since 2019-04-08
 */
@Service
@Transactional(rollbackFor = SysException.class)
@RequiredArgsConstructor
public class UserRoleServiceImpl extends SuperServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    private final RedissonClient redissonClient;

    @PostConstruct
    @Override
    public void resetUserRole() {
        // 从缓存中删除所有用户角色信息
        redissonClient.getKeys().deleteByPattern(AdminCons.Redis.USER_ROLE + "*");

        // 重新构造用户-角色数据缓存
        List<UserRoleDto> userRoleList = baseMapper.selectUserRoleList(StateEnum.ENABLE, IsDeleteEnum.NORMAL);
        userRoleList.forEach(userRoleDto -> {
            if (SysUtils.isEmpty(userRoleDto.getUserId()) || SysUtils.isEmpty(userRoleDto.getRoleId())) {
                return;
            }
            redissonClient.getMap(AdminCons.Redis.USER_ROLE + userRoleDto.getUserId())
                    .put(userRoleDto.getRoleId(), userRoleDto);
        });
    }
}
